import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 权限判断指令
import permission from '@/directive/permission/index.js'
import { getClubType } from '@/api/clubType'
import { getFacultyList, getStudent } from '@/api/school'
import { getMyClubList, getClubSelectList, setClubTime, getClubDetailByPerm, changeClubTeacher } from '@/api/club'
import { getClubMember } from '@/api/clubMember'
import { getToken } from '@/utils/auth'
import { createClubTranslation } from '@/api/clubTranslation'
import { createClubCancel } from '@/api/clubCancel'
import { createQuitClub } from '@/api/quitClub'
import { getTeacher } from '@/api/school'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

// 默认查询条件
const defaultListQuery = {
  page: 1,
  limit: 10,
  ordering: '-id',
  name: undefined,
  type: undefined,
  president: undefined
}

const defaultClubMemberListQuery = {
  is_active: 1,
  page: 1,
  limit: 10,
  club_id: undefined
}

const defaultForm = {
  id: undefined,
  name: undefined,
  is_active: 1
}

const defaultTranslationForm = {
  club_id: undefined,
  record: undefined,
  image: [],
  file: [],
  new_president_id: undefined
}

const defaultClubCancelForm = {
  club_id: undefined,
  record: undefined,
  image: [],
  file: []
}

const defaultSetTimeForm = {
  name: undefined,
  time: [],
  values: []
}

const defaultQuitClubForm = {
  name: '',
  club_id: undefined,
  reason: undefined
}

const defaultChangeTeacherForm = {
  name: '',
  club_id: undefined,
  teacher_id: undefined
}

export default {
  components: { Pagination, ElImageViewer },
  directives: { permission },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '未审核': 'info',
        '通过': 'success',
        '不通过': 'danger'
      }
      return statusMap[status]
    },
    activeTextFilter(type) {
      const typeMap = {
        true: '当前成员',
        false: '历史成员'
      }
      return typeMap[type]
    },
    activeStyleFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      loading: false,
      loadingText: '',
      total: 0,
      listQuery: Object.assign({}, defaultListQuery),
      listLoading: false,
      dataList: [],
      clubSelectList: [],
      clubTypeList: [],
      facultyList: [],
      dialogViewFormVisible: false,
      dialogStatus: '',
      dialogText: '',
      form: Object.assign({}, defaultForm),
      setTimeForm: JSON.parse(JSON.stringify(defaultSetTimeForm)),
      setTimeDialog: false,
      setTimeRules: {
        time: [{ required: true, message: '该项为必填项', trigger: 'change' }],
        values: [{ required: true, message: '该项为必填项', trigger: 'change' }]
      },
      clubOptions: [],
      props: { label: 'name', value: 'id', multiple: true, emitPath: false },
      activeName: [],

      previewImg: false,
      imgUrl: '',

      clubMemberListQuery: Object.assign({}, defaultClubMemberListQuery),
      clubMemberListLoading: false,
      clubMemberList: [],
      clubMemberDialogVisible: false,
      isActiveList: [
        { id: 1, name: '当前成员' },
        { id: 0, name: '历史成员' }
      ],
      clubMemberTotal: 0,

      translationDialog: false,
      translationRules: {
        new_president_id: [{ required: true, message: '该项为必填项', trigger: 'change' }],
        record: [{ required: true, message: '该项为必填项', trigger: 'change' }],
        image: [{ required: true, message: '文件必须上传', trigger: 'change' }],
        file: [{ required: true, message: '文件必须上传', trigger: 'change' }]
      },
      translationForm: JSON.parse(JSON.stringify(defaultTranslationForm)),
      searchLoading: false,
      studentList: [],
      transFormFileList: [],
      transFormImageList: [],

      clubCancelDialog: false,
      clubCancelRules: {
        record: [{ required: true, message: '该项为必填项', trigger: 'change' }],
        image: [{ required: true, message: '文件必须上传', trigger: 'change' }],
        file: [{ required: true, message: '文件必须上传', trigger: 'change' }]
      },
      clubCancelForm: JSON.parse(JSON.stringify(defaultClubCancelForm)),
      clubCancelFormFileList: [],
      clubCancelFileList: [],
      clubCancelImageList: [],

      headers: { Authorization: 'Bearer ' + getToken() },
      elUploadUrl: process.env.VUE_APP_BASE_API + 'api/upload/upload_img/',
      elData: { dir_name: 'club_translation' },
      fileLimitCnt: 1,
      fileLimitSize: 10,
      imageLimitCnt: 1,
      imageLimitSize: 5,

      quitClubRules: {
        reason: [{ required: true, message: '该项为必填项', trigger: 'blur' }]
      },
      quitClubDialog: false,
      quitClubForm: Object.assign({}, defaultQuitClubForm),

      changeTeacherRules: {
        teacher_id: [{ required: true, message: '该项为必填项', trigger: 'change' }]
      },
      changeTeacherDialog: false,
      changeTeacherForm: Object.assign({}, defaultChangeTeacherForm),
      teacherList: [],
      teacherInfo: {}

    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getClubType()
      this.getList()
      this.getFacultyList()
      this.getClubSelectList()
    },

    // 获取表格数据
    getList() {
      this.listLoading = true
      getMyClubList(this.listQuery).then(res => {
        this.dataList = res.results
        this.total = res.count
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 搜索事件
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 重置搜索条件
    resetFilter() {
      this.listQuery = Object.assign({}, defaultListQuery)
    },

    // 搜索社团成员
    handleClubMemberFilter() {
      this.clubMemberListQuery.page = 1
      this.getClubMember()
    },
    // 重置社团成员搜索条件
    resetClubMemberFilter() {
      this.clubMemberListQuery = Object.assign({}, defaultClubMemberListQuery)
    },

    // 获取社团分类下拉框列表
    getClubType() {
      getClubType({ is_active: true }).then(res => {
        this.clubTypeList = res
      })
    },

    // 获取社团下拉框，用于招新设置
    getClubSelectList() {
      getClubSelectList().then(res => {
        this.clubSelectList = res
        this.clubOptions = [
          { name: '社团', id: 0, children: res }
        ]
        console.log(this.clubOptions)
      })
    },

    // 获取社团成员
    getClubMember() {
      this.clubMemberListLoading = true
      getClubMember(this.clubMemberListQuery.club_id, this.clubMemberListQuery).then(res => {
        this.clubMemberList = res.results
        this.clubMemberTotal = res.count
        setTimeout(() => {
          this.clubMemberListLoading = false
        }, 0.5 * 1000)
      })
    },

    // 新会长搜索事件
    remoteMethod(query) {
      if (query !== '') {
        this.searchLoading = true
        const listQuery = { search: query }
        setTimeout(() => {
          getStudent(listQuery).then(res => {
            this.studentList = res
            this.searchLoading = false
          })
        }, 200)
      } else {
        this.studentList = []
      }
    },

    // 指导老师搜索事件
    remoteTeacherMethod(query) {
      if (query !== '') {
        this.searchLoading = true
        const listQuery = { search_key: query }
        setTimeout(() => {
          getTeacher(listQuery).then(res => {
            this.teacherList = res
            this.searchLoading = false
          })
        }, 200)
      } else {
        this.teacherList = []
      }
    },
    teacherChange(val) {
      for (var i = 0; i < this.teacherList.length; i++) {
        if (this.teacherList[i].id === val) {
          this.teacherInfo = this.teacherList[i]
          return true
        }
      }
      this.teacherInfo = {}
    },

    // 点击查看社团人员
    showClubMemberDialog(row) {
      this.clubMemberListQuery.club_id = row.id
      this.clubMemberDialogVisible = true
      this.getClubMember()
    },

    // 点击申请换届
    showTranslationDialog(row) {
      this.translationForm.club_id = row.id
      this.translationDialog = true
      this.$nextTick(() => {
        this.$refs['translationForm'].clearValidate()
      })
    },

    // 点击更换社团指导老师
    showChangeTeacherDialog(row) {
      this.changeTeacherForm = row
      this.changeTeacherForm.club_id = row.id
      this.remoteTeacherMethod(row.teacher_realname)
      this.teacherInfo = { username: row.teacher_username, realname: row.teacher_realname, faculty_title: row.teacher_faculty_title }
      this.changeTeacherDialog = true
      this.$nextTick(() => {
        this.$refs['changeTeacherForm'].clearValidate()
      })
    },

    // 点击注销社团
    showClubCancelDialog(row) {
      this.clubCancelForm.club_id = row.id
      this.clubCancelDialog = true
      this.$nextTick(() => {
        this.$refs['clubCancelForm'].clearValidate()
      })
    },

    // 获取二级单位下拉框列表
    getFacultyList() {
      getFacultyList().then(res => {
        this.facultyList = res.data
      })
    },

    // 前往新建社团页面
    goCreate() {
      this.$router.push({
        name: 'CreateClub'
      })
    },
    // 前往更新社团页面
    goUpdate(row) {
      this.$router.push({
        name: 'UpdateClub',
        query: { club: row.id }
      })
    },

    // 点击查看详情事件
    showViewDialog(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在获取数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getClubDetailByPerm(row.id).then(res => {
        loading.close()
        this.form = res
        this.form.first_check_status = ''
      }).catch((error) => {
        this.$message.error(error.response.data.message)
      })
      // this.form = Object.assign({}, row)
      this.dialogStatus = 'view'
      this.dialogText = row.title
      this.dialogViewFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },

    // 点击设置招新
    showSetTimeDialog() {
      this.setTimeForm = JSON.parse(JSON.stringify(defaultSetTimeForm))
      this.setTimeDialog = true
      this.$nextTick(() => {
        this.$refs['setTimeForm'].clearValidate()
      })
    },

    // 点击退出社团
    showClubQuitDialog(row) {
      this.quitClubDialog = true
      this.quitClubForm.club_id = row.id
      this.quitClubForm.name = row.name
      this.$nextTick(() => {
        this.$refs['quitClubForm'].clearValidate()
      })
    },

    // 进行招新时间设置
    setTime() {
      this.$refs['setTimeForm'].validate((valid) => {
        if (valid) {
          this.setTimeForm.apply_start_time = this.setTimeForm.time[0]
          this.setTimeForm.apply_end_time = this.setTimeForm.time[1]
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          setClubTime(this.setTimeForm).then(response => {
            loading.close()
            this.setTimeDialog = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        } else {
          console.log('表单出错')
        }
      })
    },

    // 创建换届申请
    createTranslation() {
      this.$refs['translationForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          createClubTranslation(this.translationForm).then(response => {
            loading.close()
            this.translationDialog = false
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        } else {
          console.log('表单出错')
        }
      })
    },

    // 创建注销社团申请
    createClubCancel() {
      this.$refs['clubCancelForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          createClubCancel(this.clubCancelForm).then(response => {
            loading.close()
            this.clubCancelDialog = false
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        } else {
          console.log('表单出错')
        }
      })
    },

    // 创建退团申请
    createQuitClub() {
      this.$refs['quitClubForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          createQuitClub(this.quitClubForm).then(response => {
            loading.close()
            this.quitClubDialog = false
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        } else {
          console.log('表单出错')
        }
      })
    },

    // 进行更换指导老师
    createChangeTeacher() {
      this.$refs['changeTeacherForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          changeClubTeacher(this.changeTeacherForm.id, this.changeTeacherForm).then(response => {
            loading.close()
            this.changeTeacherDialog = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        } else {
          console.log('表单出错')
        }
      })
    },

    // 上传文件之前的钩子
    beforeUpload(file, typeName, limit = 10) {
      // 限制文件上传大小, 大于1M则提示, 且不请求提交表单
      const flag = file.size / 1024 / 1024 < limit
      if (!flag) {
        this.$message.error('上传文件大小不能超过' + limit + 'M')
        return false
      }
    },
    // 上传文件数量超出自定义数量
    handleExceed(files, fileList) {
      this.$message.warning('已达到最大上传数量, 请删除后继续上传')
    },
    handleProgress(event, file, fileList) {
      this.loading = true
      this.loadingText = '正在上传文件....'
    },
    // 上传成功回调
    handleSuccess(response, typeName) {
      this.loading = false
      this.$message({
        message: '上传文件成功',
        type: 'success'
      })
      if (typeName === 'trans_file') {
        this.translationForm.file.push(response)
        this.$refs.translationForm.validateField('file')
      } else if (typeName === 'trans_image') {
        this.translationForm.image.push(response)
        this.$refs.translationForm.validateField('image')
      } else if (typeName === 'club_cancel_image') {
        this.clubCancelForm.image.push(response)
        this.$refs.clubCancelForm.validateField('image')
      } else if (typeName === 'club_cancel_file') {
        this.clubCancelForm.file.push(response)
        this.$refs.clubCancelForm.validateField('file')
      }
    },
    // 上传失败
    handleError(res_error, file, fileList) {
      this.loading = false
      this.$message({
        message: '上传文件失败',
        type: 'danger'
      })
    },
    // 文件列表移除文件
    handleRemove(file, typeName) {
      let key = ''
      if (file.response) {
        key = file.response.data
      } else {
        key = file.url
      }
      var i = 0
      if (typeName === 'trans_file') {
        for (i = 0; i < this.translationForm.file.length; i++) {
          if (key.indexOf(this.translationForm.file[i].data) !== -1) {
          // if (key.match(this.translationForm.file[i].data)) {
            this.translationForm.file.splice(i, 1)
            break
          }
        }
      } else if (typeName === 'trans_image') {
        for (i = 0; i < this.translationForm.image.length; i++) {
          if (key.indexOf(this.translationForm.image[i].data) !== -1) {
          // if (key.match(this.translationForm.image[i].data)) {
            this.translationForm.image.splice(i, 1)
            break
          }
        }
      } else if (typeName === 'club_cancel_image') {
        for (i = 0; i < this.clubCancelForm.image.length; i++) {
          if (key.match(this.clubCancelForm.image[i].data)) {
            this.clubCancelForm.image.splice(i, 1)
            break
          }
        }
      } else if (typeName === 'club_cancel_file') {
        for (i = 0; i < this.clubCancelForm.file.length; i++) {
          if (key.match(this.clubCancelForm.file[i].data)) {
            this.clubCancelForm.file.splice(i, 1)
            break
          }
        }
      }
    },

    // 预览图片
    previewImage(file) {
      this.previewImg = true
      this.imgUrl = file.url
      // this.$refs.viewer.$viewer.show()
    },

    previewFile(file) {
      window.open(file.url)
    }

  }
}
